#include "stdafx.h"
#include "net/AbstractHTTPRequestHandler.hpp"
#include "net/HTMLForm.hpp"
#include "stdlib/exception.hpp"
using namespace JHCPP::stdlib;
#include "utils/numberformatter.hpp"
using JHCPP::utils::CNumberFormatter;

NET_NAMESPACE_BEGIN

CAbstractHTTPRequestHandler::CAbstractHTTPRequestHandler()
	: m_pRequest(0), m_pResponse(0), m_pForm(0)
{
}

CAbstractHTTPRequestHandler::~CAbstractHTTPRequestHandler()
{
	delete m_pForm;
}

void CAbstractHTTPRequestHandler::handleRequest(CHTTPServerRequest& request, CHTTPServerResponse& response)
{
	m_pRequest  = &request;
	m_pResponse = &response;
	if (authenticate())
	{
		try
		{
			run();
		}
		catch (CException& exc)
		{
			if (!response.sent())
			{
				sendErrorResponse(CHTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.displayText());
			}
		}
		catch (std::exception& exc)
		{
			if (!response.sent())
			{
				sendErrorResponse(CHTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.what());
			}
		}
	}
	else
	{
		sendErrorResponse(CHTTPResponse::HTTP_UNAUTHORIZED, "");
	}
}

bool CAbstractHTTPRequestHandler::authenticate()
{
	return true;
}

CHTMLForm& CAbstractHTTPRequestHandler::form()
{
	if (!m_pForm)
		m_pForm = new CHTMLForm(request(), request().stream());

	return *m_pForm;
}

void CAbstractHTTPRequestHandler::sendErrorResponse(CHTTPResponse::HTTPStatus status, const std::string& message)
{
	response().setStatusAndReason(status);
	std::string statusAndReason(CNumberFormatter::format(static_cast<int>(response().getStatus())));
	statusAndReason += " - ";
	statusAndReason += response().getReason();
	std::string page("<HTML><HEAD><TITLE>");
	page += statusAndReason;
	page += "</TITLE></HEAD><BODY><H1>";
	page += statusAndReason;
	page += "</H1>";
	page += "<P>";
	page += message;
	page += "</P></BODY></HTML>";
	response().sendBuffer(page.data(), page.size());
}

CHTTPServerRequest& CAbstractHTTPRequestHandler::request()
{
	jh_check_ptr (m_pRequest);

	return *m_pRequest;
}

CHTTPServerResponse& CAbstractHTTPRequestHandler::response()
{
	jh_check_ptr (m_pResponse);

	return *m_pResponse;
}

NET_NAMESPACE_END
